package com.th.supcom.pds.impl.service.internal;

import java.util.ArrayList;
import java.util.List;

import net.carefx.fc.framework.web.gwt.util.FcUtils;
import net.carefx.framework.exception.BusinessException;
import net.carefx.framework.translate.TranslatorManager;
import net.carefx.framework.util.ConvertUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.th.supcom.pds.domain.pojo.PdsPresc;
import com.th.supcom.pds.domain.pojo.PdsPrescDetail;
import com.th.supcom.pds.domain.pojo.PdsPrescDetailCombine;
import com.th.supcom.pds.domain.vo.PatientInfo;
import com.th.supcom.pds.domain.vo.PdsPrescDetailAndPrescVo;
import com.th.supcom.pds.domain.vo.PrescAndPatiResult;
import com.th.supcom.pds.impl.common.PdsConstants;
import com.th.supcom.pds.impl.common.enums.ChargeIndicator;
import com.th.supcom.pds.impl.common.enums.DispenseIndicator;
import com.th.supcom.pds.impl.common.enums.PrescSupplyDrugState;
import com.th.supcom.pds.impl.common.enums.QualifiedIndicator;
import com.th.supcom.pds.impl.common.enums.SortingIdentification;
import com.th.supcom.pds.impl.common.enums.WithdrawalDrugState;
import com.th.supcom.pds.internal.api.DrugReturnService;
import com.th.supcom.pds.internal.api.PdsSupplyDetailService;
import com.th.supcom.pds.internal.api.PdsSupplyService;
import com.th.supcom.pds.medicare.api.AdapterDrugManagerService;
import com.th.supcom.pds.medicare.api.AdapterPtsExtOutPatientVisitService;

/**
 * @author yzhang
 */
public class DrugReturnServiceImpl implements DrugReturnService
{
    private PdsSupplyService m_pdsSupplyService;
    private PdsSupplyDetailService m_pdsSupplyDetailService;
    private TranslatorManager m_translatorManager;
    private AdapterPtsExtOutPatientVisitService m_adapterPtsExtOutPatientVisitService;
    private AdapterDrugManagerService m_adapterDrugManagerService;

    public void setPdsSupplyService (PdsSupplyService pdsSupplyService)
    {
    
        m_pdsSupplyService = pdsSupplyService;
    }

    public void setPdsSupplyDetailService (PdsSupplyDetailService pdsSupplyDetailService)
    {
    
        m_pdsSupplyDetailService = pdsSupplyDetailService;
    }

    /**
     * 用于门诊退药处方状态查询
     */
    @Override
    public PrescAndPatiResult getPrescDetailForReturn (List <String> prescNoList, String performedBy)
    {

        s_logger.debug ("进入findPrescDetailForReturn方法,入参:prescNoList,o{},performedBy:{}", new Object[]
        { prescNoList, performedBy });
        PrescAndPatiResult prescAndPatiResult = new PrescAndPatiResult ();

        List <List <PdsPrescDetailAndPrescVo>> prescDetailAndPrescList = new ArrayList <List <PdsPrescDetailAndPrescVo>> ();
        try
        {
            for (String prescNo : prescNoList)
            {
                PdsPrescDetailAndPrescVo vo = new PdsPrescDetailAndPrescVo ();
                vo.setPrescNo (prescNo);
                vo.setPperformedBy (performedBy);
               List <PdsPrescDetailAndPrescVo> list =null; 
               //m_pdsPrescDetailManager.getPrescDetailForReturn (vo);
                if (list.isEmpty ())
                {
                    continue;
                }
                list = m_translatorManager.translate (list);
                prescDetailAndPrescList.add (list);

            }
        }
        catch (Exception e)
        {
            s_logger.error ("查询处方信息出现异常" + e.getLocalizedMessage ());
            throw new BusinessException ("查询处方信息出现异常，请联系计算机中心！", e);
        }
        if (1 == prescNoList.size ())
        {
            if(prescDetailAndPrescList.isEmpty ()){
               return prescAndPatiResult;
            }
            // 得到患者信息
            Long pVisitId = prescDetailAndPrescList.get (0).get (0).getPatientVisitId ();
            String patientId = prescDetailAndPrescList.get (0).get (0).getPatientId ();
            if (pVisitId == null)
            {
                throw new BusinessException ("查询失败，相关处方找不到患者ID");
            }
            PatientInfo patientInfo = null;
            try
            {
                patientInfo = m_adapterPtsExtOutPatientVisitService.getPatientInfo (pVisitId,
                                                                                    prescDetailAndPrescList.get (0)
                                                                                                           .get (0)
                                                                                                           .getPrescSource (),
                                                                                    patientId);
            }
            catch (Exception e)
            {
                s_logger.error ("查询患者信息出现异常" + e.getLocalizedMessage ());
                throw new BusinessException ("查询患者信息出现异常，请联系计算机中心！", e);
            }
            if (patientInfo == null)
            {
                throw new BusinessException ("查询患者信息出现异常，请联系计算机中心！");
            }
            prescAndPatiResult.setPatientInfo (patientInfo);
        }
        prescAndPatiResult.setList (prescDetailAndPrescList);

        return prescAndPatiResult;

    }

    /**
     * 门诊退药通过 1.处方持久化2.退药入库3.回写处方信息4.回写医嘱处方信息
     */
    @Override
    public void drugReturnPass (List <PdsPrescDetailAndPrescVo> prescList,
                                List <PdsPrescDetailAndPrescVo> prescDetailList, String operator)
    {
        // 1.处方持久化，拒绝人，拒绝时间，批次，有效期
        persistent (prescList, prescDetailList, operator);
        // 2调用接口 完成退药入库
        List <PdsPrescDetailCombine> stockInList = new ArrayList <PdsPrescDetailCombine> ();
        for (int i = 0; i < prescDetailList.size (); i++)
        {
            PdsPrescDetailAndPrescVo vo = prescDetailList.get (i);
            PdsPrescDetailCombine stockIn = new PdsPrescDetailCombine ();
            stockIn.setPatientId (vo.getPatientId ());
            stockIn.setPerformedBy (vo.getPperformedBy ());
            stockIn.setPackageQuantity (vo.getPackageQuantity ());
            stockIn.setQuantity (vo.getQuantity ());
            stockIn.setPackageUnits (vo.getPackageUnits ());
            stockIn.setUnits (vo.getUnits ());
            stockIn.setPrescDetailNo (vo.getPrescDetailNo ());
            stockIn.setReceiptDate (vo.getReceiptDate ());
            stockIn.setPhamBatchNumber (vo.getPhamBatchNumber ());
            stockIn.setPhamCode (vo.getPhamCode ());
            stockIn.setFactor (vo.getFactor ());
            stockInList.add (stockIn);
        }
        try
        {
           // m_adapterDrugManagerService.drugStockIn (stockInList, operator);
        }
        catch (Exception e)
        {
            s_logger.error ("退药入库出现异常" + e.getLocalizedMessage (), e);
            throw new BusinessException ("退药入库出现异常" + PdsConstants.DEFALUT_HTML_WRAP, e);
        }
        // 3回写pds处方信息,修改退药状态为：已退,退费已申请
        List <PdsPresc> pdsPrescs = ConvertUtils.convert (PdsPresc.class, prescList);
        for (PdsPresc pdsPresc : pdsPrescs)
        {
            pdsPresc.setChargeIndicator (ChargeIndicator.Applied.getEnumCode ());
            pdsPresc.setRefundAppl (operator);
            pdsPresc.setRefundApplTime (FcUtils.getCurrentServerDateTimeForServer ());
        }
        try
        {
            //m_pdsPrescManager.modifyPdsPrescListForReturn (pdsPrescs);
        }
        catch (Exception e)
        {
            s_logger.error ("回写处方信息出现异常" + e.getLocalizedMessage (), e);
            throw new BusinessException ("回写处方信息出现异常" + PdsConstants.DEFALUT_HTML_WRAP, e);
        }
    }

    /**
     * 门诊退药被拒绝 1.处方持久化 2.回写医嘱处方信息
     */
    @Override
    public void drugReturnRefuse (List <PdsPrescDetailAndPrescVo> prescList,
                                  List <PdsPrescDetailAndPrescVo> prescDetailList, String operator)
    {
        // 1.处方持久化，拒绝人，拒绝时间，批次，有效期
        persistent (prescList, prescDetailList, operator);

        // 回写医嘱处方

    }

    /**
     * @param lists
     */
    private void persistent (List <PdsPrescDetailAndPrescVo> prescList,
                             List <PdsPrescDetailAndPrescVo> prescDetailList, String operator)
    {
        try
        {
            // 处方持久化
            for (PdsPrescDetailAndPrescVo prescVo : prescList)
            {
                PdsPresc pdsPresc = ConvertUtils.convert (PdsPresc.class, prescVo);
                pdsPresc.setPrescriptionTime (FcUtils.getCurrentServerDateTimeForServer ());
                pdsPresc.setWithdrawalDrugState (WithdrawalDrugState.UnReturn.getEnumCode ());
                pdsPresc.setQualifiedIndicator (QualifiedIndicator.Qualified.getEnumCode ());
                pdsPresc.setPrescSupplyDrugState (PrescSupplyDrugState.Undispensed.getEnumCode ());
                pdsPresc.setChargeIndicator (ChargeIndicator.Uncharged.getEnumCode ());
                pdsPresc.setDrugReturn (operator);
                pdsPresc.setDrugReturnTime (FcUtils.getCurrentServerDateTimeForServer ());
                //m_pdsPrescService.persistentPdsPresc (pdsPresc);
            }
            // 处方明细持久化
            for (PdsPrescDetailAndPrescVo prescDetailVo : prescDetailList)
            {
                PdsPrescDetail pdsPrescDetail = ConvertUtils.convert (PdsPrescDetail.class, prescDetailVo);
                pdsPrescDetail.setPerformedBy (prescDetailVo.getPperformedBy ());
                pdsPrescDetail.setReceiptDate (prescDetailVo.getReceiptDate ());
                pdsPrescDetail.setPhamBatchNumber (prescDetailVo.getPhamBatchNumber ());
                pdsPrescDetail.setSortingIdentification (SortingIdentification.Unsorted.getEnumCode ());
                pdsPrescDetail.setDispenseIndicator (DispenseIndicator.Undispensed.getEnumCode ());
               // m_pdsPrescDetailService.persistentPrescDetail (pdsPrescDetail);
            }
        }
        catch (Exception e)
        {
            s_logger.error ("处方持久化出错" + e.getLocalizedMessage (), e);
            throw new BusinessException ("处方持久化出错" + PdsConstants.DEFALUT_HTML_WRAP, e);
        }
    }

    public void setTranslatorManager (TranslatorManager translatorManager)
    {
        m_translatorManager = translatorManager;
    }


    public void setAdapterDrugManagerService (AdapterDrugManagerService adapterDrugManagerService)
    {
        m_adapterDrugManagerService = adapterDrugManagerService;
    }

    public void setAdapterPtsExtOutPatientVisitService (AdapterPtsExtOutPatientVisitService adapterPtsExtOutPatientVisitService)
    {
        m_adapterPtsExtOutPatientVisitService = adapterPtsExtOutPatientVisitService;
    }

    /** 日志记录器. */
    public static final Logger s_logger = LoggerFactory.getLogger (DrugReturnServiceImpl.class);

    /** 公司版权信息. */
    public static final String copyright = "Copyright 2014, XuNuo Corporation";

    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";

    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";
}
